<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/18
 * Time: 11:26
 */

namespace backend\modules\qywx\components\authclient;


use common\business\QywxHelper;
use yii\authclient\OAuth2;
use yii\authclient\OAuthToken;
use yii\web\HttpException;

class QywxAuth extends OAuth2
{
    protected function initUserAttributes()
    {
        //这一步是拿认证后的用户 详细信息，供AuthHandler处理，比如绑定会员、添加新会员等。逻辑自行处理
        $oauthToken = $this->getAccessToken();
//        返回格式如下:
//        ?code=0SLMlX_6i4B5jn-VFeLCmo4TQkqWNyfzWrJDpy4oDtQ&state=web_login@gyoss9&appid=wxd11fdf2cc211b34a

        $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo';
        $get_params = [
            'code' => $oauthToken->params['code'],
            'access_token' => QywxHelper::getAccessTokenVal(),
        ];

        $response = $this->api($url, 'GET', $get_params);
        return $response;
    }

    //拿到code后也就是$authCode去拿accessToken;拿到后传给AuthHandler，并再拿到一个authclient对象。
    public function fetchAccessToken($authCode, array $params = [])
    {
        if ($this->validateAuthState) {
            $authState = $this->getState('authState');
            if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) {
                throw new HttpException(400, 'Invalid auth state parameter.');
            } else {
                $this->removeState('authState');
            }
        }
        $defaultParams = [
            'appid' => $this->clientId,
            'secret' => $this->clientSecret,
            'code' => $authCode,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $this->getReturnUrl(),
        ];
        $request = $this->createRequest()
            ->setMethod('GET')
            ->setUrl($this->tokenUrl)
            ->setData(array_merge($defaultParams, $params));
        $response = $this->sendRequest($request);
        $token = $this->createToken(['params' => $response]);
        $this->setAccessToken($token);
        return $token;
    }

    public function refreshAccessToken(OAuthToken $token)
    {//刷新accesstoken这一步我还没有测试。
        $params = [
            'appid' => $this->clientId,
            'grant_type' => 'refresh_token',
            'refresh_token' => $this->clientSecret,
        ];
        $params = array_merge($token->getParams(), $params);
        $request = $this->createRequest()
            ->setMethod('POST')
            ->setUrl($this->refreshUrl)
            ->setData($params);
        $response = $this->sendRequest($request);
        $token = $this->createToken(['params' => $response]);
        $this->setAccessToken($token);
        return $token;
    }

    protected function defaultName()
    {
        return 'qywx';
    }

    protected function defaultTitle()
    {
        return 'qywx';
    }
}